<template>
  <view class="page-container" :class="themeClass">
    <!-- 自定义导航栏 -->
    <CustomNavBar 
      :title="isEdit ? '编辑分类' : '创建分类'" 
      :show-back="true"
      @back="handleBack"
      @rightClick="handleSave"
    >
      <template #right>
        <text class="save-btn" :class="{ disabled: !canSave }">{{ saving ? '保存中' : '保存' }}</text>
      </template>
    </CustomNavBar>
    
    <!-- 页面内容 -->
    <view class="page-content" :style="{ paddingTop: navBarHeight + 'px' }">
      <scroll-view scroll-y class="content-scroll">
        <!-- 分类预览 -->
        <view class="preview-section">
          <view class="preview-card">
            <view class="preview-icon" :style="{ backgroundColor: formData.color + '20' }">
              <text class="icon-text">{{ formData.icon || '📁' }}</text>
            </view>
            <view class="preview-info">
              <text class="preview-name">{{ formData.name || '分类名称' }}</text>
              <text class="preview-desc">{{ formData.description || '分类描述' }}</text>
            </view>
          </view>
        </view>
        
        <!-- 表单内容 -->
        <view class="form-section">
          <!-- 分类名称 -->
          <view class="form-group">
            <text class="form-label">分类名称 <text class="required">*</text></text>
            <input
              class="simple-input"
              v-model="formData.name"
              placeholder="请输入分类名称"
              maxlength="20"
            />
          </view>
          
          <!-- 分类描述 -->
          <view class="form-group">
            <text class="form-label">分类描述</text>
            <textarea
              class="simple-textarea"
              v-model="formData.description"
              placeholder="请输入分类描述（可选）"
              maxlength="100"
            ></textarea>
          </view>
          
          <!-- 分类图标 -->
          <view class="form-group">
            <text class="form-label">分类图标</text>
            <view class="icon-section">
              <view class="current-icon" @click="showIconModal = true">
                <view class="icon-display" :style="{ backgroundColor: formData.color + '20' }">
                  <text class="icon-text">{{ formData.icon || '📁' }}</text>
                </view>
                <text class="icon-label">点击选择图标</text>
              </view>
              
              <view class="icon-grid">
                <view 
                  class="icon-item" 
                  v-for="icon in iconOptions.slice(0, 8)" 
                  :key="icon"
                  :class="{ active: formData.icon === icon }"
                  @click="selectIcon(icon)"
                >
                  <text class="icon-emoji">{{ icon }}</text>
                </view>
                <view class="icon-item more-icon" @click="showIconModal = true">
                  <uni-icons type="more-filled" size="20" color="#999"></uni-icons>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 分类颜色 -->
          <view class="form-group">
            <text class="form-label">分类颜色</text>
            <view class="color-section">
              <view class="color-grid">
                <view 
                  class="color-item" 
                  v-for="color in colorOptions" 
                  :key="color"
                  :class="{ active: formData.color === color }"
                  :style="{ backgroundColor: color }"
                  @click="selectColor(color)"
                >
                  <uni-icons v-if="formData.color === color" type="checkmarkempty" size="16" color="#ffffff"></uni-icons>
                </view>
              </view>
              
              <!-- 自定义颜色 -->
              <view class="custom-color">
                <text class="custom-label">自定义颜色</text>
                <input 
                  type="color" 
                  v-model="formData.color"
                  class="color-picker"
                />
              </view>
            </view>
          </view>
        </view>
        
        <!-- 删除按钮（编辑模式） -->
        <view class="delete-section" v-if="isEdit">
          <button class="delete-btn" @click="handleDelete">
            <uni-icons type="trash" size="18" color="#ff4d4f"></uni-icons>
            <text class="delete-text">删除分类</text>
          </button>
        </view>
      </scroll-view>
    </view>
    
    <!-- 图标选择弹窗 -->
    <IconSelectModal
      v-model:show="showIconModal"
      :selected="formData.icon"
      :options="iconOptions"
      @select="selectIcon"
    />
    
    <!-- 加载组件 -->
    <LoadingComponent :visible="loading || saving" :text="saving ? '保存中...' : '加载中...'" />
  </view>
</template>

<script>
import { useDiaryStore } from '@/store/diary'
import { useUserStore } from '@/store/user'
import { 
  getCategoryDetailAPI, 
  createCategoryAPI, 
  updateCategoryAPI,
  deleteCategoryAPI 
} from '@/api/category'
import { extractResponseData } from '@/utils/index'
import CustomNavBar from '@/components/CustomNavBar.vue'
import LoadingComponent from '@/components/LoadingComponent.vue'
import IconSelectModal from '@/components/IconSelectModal.vue'

export default {
  name: 'CategoryEditPage',
  components: {
    CustomNavBar,
    LoadingComponent,
    IconSelectModal
  },
  setup() {
    const diaryStore = useDiaryStore()
    const userStore = useUserStore()
    
    return {
      diaryStore,
      userStore
    }
  },
  data() {
    return {
      navBarHeight: 88,
      categoryId: null,
      isEdit: false,
      loading: false,
      saving: false,
      showIconModal: false,
      
      formData: {
        name: '',
        description: '',
        icon: '📁',
        color: '#1890ff'
      },
      
      // 图标选项
      iconOptions: [
        '📁', '📝', '💼', '🎯', '💡', '🎨', '🏠', '🍔',
        '✈️', '📚', '💰', '🎵', '🏃', '🎮', '📱', '🌟',
        '🔥', '💎', '🌈', '⚡', '🎪', '🎭', '🎨', '🎯',
        '📊', '📈', '📉', '📋', '📌', '📎', '🔍', '🔧'
      ],
      
      // 颜色选项
      colorOptions: [
        '#1890ff', '#52c41a', '#faad14', '#f5222d',
        '#722ed1', '#eb2f96', '#13c2c2', '#fa541c',
        '#2f54eb', '#a0d911', '#fadb14', '#ff4d4f',
        '#9254de', '#f759ab', '#36cfc9', '#ff7a45'
      ]
    }
  },
  computed: {
    themeClass() {
      return this.userStore.themeMode === 'dark' ? 'theme-dark' : 'theme-light'
    },
    
    canSave() {
      return this.formData.name.trim() && !this.saving
    }
  },
  onLoad(options) {
    this.categoryId = options.id
    this.isEdit = !!this.categoryId
    this.initPage()
  },
  methods: {
    async initPage() {
      // 检查登录状态
      if (!this.userStore.checkLoginStatus()) return
      
      // 获取导航栏高度
      const systemInfo = uni.getSystemInfoSync()
      this.navBarHeight = systemInfo.statusBarHeight + 44
      
      // 如果是编辑模式，加载分类详情
      if (this.isEdit) {
        await this.loadCategoryDetail()
      }
    },
    
    async loadCategoryDetail() {
      if (!this.categoryId) return
      
      this.loading = true
      
      try {
        const res = await getCategoryDetailAPI(this.categoryId)
        const category = extractResponseData(res)
        
        this.formData = {
          name: category.name || '',
          description: category.description || '',
          icon: category.icon || '📁',
          color: category.color || '#1890ff'
        }
        
      } catch (error) {
        console.error('加载分类详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } finally {
        this.loading = false
      }
    },
    
    // 处理返回
    async handleBack() {
      if (this.hasUnsavedChanges()) {
        try {
          await uni.showModal({
            title: '提示',
            content: '有未保存的内容，确定要离开吗？',
            showCancel: true
          })
          uni.navigateBack()
        } catch (error) {
          // 用户取消
        }
      } else {
        uni.navigateBack()
      }
    },
    
    // 检查是否有未保存的更改
    hasUnsavedChanges() {
      return this.formData.name.trim() || this.formData.description.trim()
    },
    
    // 处理保存
    async handleSave() {
      if (!this.canSave) return
      
      if (!this.validateForm()) return
      
      this.saving = true
      
      try {
        const data = {
          name: this.formData.name.trim(),
          description: this.formData.description.trim(),
          icon: this.formData.icon,
          color: this.formData.color
        }
        
        let res
        if (this.isEdit) {
          res = await updateCategoryAPI(this.categoryId, data)
        } else {
          res = await createCategoryAPI(data)
        }
        
        const savedCategory = extractResponseData(res)
        
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })
        
        // 更新状态管理
        if (this.isEdit) {
          this.diaryStore.updateCategory(savedCategory)
        } else {
          this.diaryStore.addCategory(savedCategory)
        }
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        console.error('保存失败:', error)
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })
      } finally {
        this.saving = false
      }
    },
    
    // 表单验证
    validateForm() {
      if (!this.formData.name.trim()) {
        uni.showToast({
          title: '请输入分类名称',
          icon: 'none'
        })
        return false
      }
      
      if (this.formData.name.trim().length < 2) {
        uni.showToast({
          title: '分类名称至少2个字符',
          icon: 'none'
        })
        return false
      }
      
      return true
    },
    
    // 选择图标
    selectIcon(icon) {
      this.formData.icon = icon
      this.showIconModal = false
    },
    
    // 选择颜色
    selectColor(color) {
      this.formData.color = color
        },
    
    // 删除分类
    async handleDelete() {
      try {
        await uni.showModal({
          title: '确认删除',
          content: `确定要删除分类"${this.formData.name}"吗？\n删除后该分类下的日记将变为未分类状态。`,
          showCancel: true,
          confirmColor: '#ff4d4f'
        })
        
        this.loading = true
        
        await deleteCategoryAPI(this.categoryId)
        
        // 更新状态管理
        this.diaryStore.deleteCategory(this.categoryId)
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        if (error.errMsg !== 'showModal:fail cancel') {
          console.error('删除分类失败:', error)
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.content-scroll {
  height: calc(100vh - 88px);
  padding-bottom: 120rpx;
}

.preview-section {
  padding: 40rpx 32rpx;
  background-color: #f8f8f8;
}

.preview-card {
  display: flex;
  align-items: center;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 32rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.preview-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
}

.icon-text {
  font-size: 32rpx;
}

.preview-info {
  flex: 1;
}

.preview-name {
  display: block;
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
  margin-bottom: 8rpx;
}

.preview-desc {
  font-size: 26rpx;
  color: #666666;
  line-height: 1.4;
}

.form-section {
  padding: 0 32rpx;
}

.form-group {
  margin-bottom: 40rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 16rpx;
}

.required {
  color: #ff4d4f;
}

.simple-input {
  width: 100%;
  height: 88rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  background-color: #ffffff;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  color: #333333;
  outline: none;
}

.simple-input:focus {
  border-color: #1890ff;
}

.simple-input::placeholder {
  color: #999999;
}

.simple-textarea {
  width: 100%;
  min-height: 120rpx;
  padding: 24rpx;
  font-size: 28rpx;
  background-color: #ffffff;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  color: #333333;
  outline: none;
  resize: vertical;
  line-height: 1.4;
}

.simple-textarea:focus {
  border-color: #1890ff;
}

.simple-textarea::placeholder {
  color: #999999;
}



.icon-section {
  margin-top: 16rpx;
}

.current-icon {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 24rpx;
}

.icon-display {
  width: 80rpx;
  height: 80rpx;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-label {
  font-size: 26rpx;
  color: #666666;
}

.icon-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 16rpx;
}

.icon-item {
  width: 80rpx;
  height: 80rpx;
  border-radius: 12rpx;
  background-color: #f8f8f8;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx solid transparent;
  transition: all 0.3s;
}

.icon-item.active {
  background-color: #e6f7ff;
  border-color: #1890ff;
}

.icon-item.more-icon {
  background-color: #f0f0f0;
}

.icon-emoji {
  font-size: 28rpx;
}

.color-section {
  margin-top: 16rpx;
}

.color-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 16rpx;
  margin-bottom: 32rpx;
}

.color-item {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx solid transparent;
  transition: all 0.3s;
}

.color-item.active {
  border-color: #333333;
  transform: scale(1.1);
}

.custom-color {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx;
  background-color: #f8f8f8;
  border-radius: 12rpx;
}

.custom-label {
  font-size: 28rpx;
  color: #333333;
}

.color-picker {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  border: none;
  background-color: transparent;
}

.delete-section {
  padding: 0 32rpx 40rpx;
}

.delete-btn {
  width: 100%;
  height: 88rpx;
  background-color: #ffffff;
  border: 2rpx solid #ff4d4f;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
  font-size: 28rpx;
  color: #ff4d4f;
}

.delete-btn::after {
  border: none;
}

.delete-text {
  font-size: 28rpx;
  color: #ff4d4f;
}

.save-btn {
  font-size: 28rpx;
  color: #1890ff;
}

.save-btn.disabled {
  color: #cccccc;
}

/* 页面容器样式 */
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 主题适配 */
.theme-light.page-container {
  background-color: #f5f5f5 !important;
}

.theme-dark.page-container {
  background-color: #1e1e1e !important;
}

.theme-dark .preview-section {
  background-color: #2d2d30;
}

.theme-dark .preview-card {
  background-color: #252526;
}

.theme-dark .preview-name,
.theme-dark .form-label,
.theme-dark .custom-label {
  color: #e8e8e8;
}

.theme-dark .preview-desc,
.theme-dark .icon-label {
  color: #b3b3b3;
}

.theme-dark .simple-input,
.theme-dark .simple-textarea {
  background-color: #252526;
  border-color: #404040;
  color: #e8e8e8;
}

.theme-dark .simple-input:focus,
.theme-dark .simple-textarea:focus {
  border-color: #1890ff;
}

.theme-dark .simple-input::placeholder,
.theme-dark .simple-textarea::placeholder {
  color: #8c8c8c;
}

.theme-dark .icon-item {
  background-color: #404040;
}

.theme-dark .icon-item.active {
  background-color: #1890ff;
}

.theme-dark .icon-item.more-icon {
  background-color: #2d2d30;
}

.theme-dark .custom-color {
  background-color: #2d2d30;
}

.theme-dark .delete-btn {
  background-color: #252526;
  border-color: #ff4d4f;
}
</style> 